<?php
if (!defined('ABSPATH')) {
    exit();
}

/*
|--------------------------------------------------------------------------
| getting single coin details
|--------------------------------------------------------------------------
 */
function cmc_get_coin_details($coin_id)
{
    $api_hit = cmc_update_single_coin_data($coin_id);
    if (is_array($api_hit) && isset($api_hit[0])) {
        $coin_data = objectToArray($api_hit[0]);
        return $coin_data;
    }
    $cmcDB = new CMC_Coins;
    $coin_data = $cmcDB->get_coins(array('coin_id' => $coin_id));
    if (is_array($coin_data) && isset($coin_data[0])) {
        $coin_data = objectToArray($coin_data[0]);
        return $coin_data;
    } else {
        return false;
    }
}

/*
|--------------------------------------------------------------------------
| getting coin meta
|--------------------------------------------------------------------------
 */
function cmc_get_coin_meta($coin_id)
{

    $cmcMetaDB = new CMC_Coins_Meta;
    CMC_api_data::cmc_select_social_data_api($coin_id);
    if ($cmcMetaDB->coin_exists_by_id($coin_id) == true) {
        $coin_data = $cmcMetaDB->get_coins_meta_data(array('coin_id' => $coin_id));
        if (is_array($coin_data) && isset($coin_data[0]->extra_data)) {
            return unserialize($coin_data[0]->extra_data);
        }

    } else {
        CMC_api_data::cmc_select_social_data_api($coin_id);
        $coin_data = $cmcMetaDB->get_coins_meta_data(array('coin_id' => $coin_id));
        if (is_array($coin_data) && isset($coin_data[0]->extra_data)) {
            return unserialize($coin_data[0]->extra_data);
        } else {
            return false;
        }
    }

}

/*
|--------------------------------------------------------------------------
| getting coin single page description
|--------------------------------------------------------------------------
 */
function cmc_get_coin_desc($coin_id)
{
    $cmcMetaDB = new CMC_Coins_Meta;
    if ($cmcMetaDB->coin_exists_by_id($coin_id) == true) {
        $coin_data = $cmcMetaDB->get_coins_desc(array('coin_id' => $coin_id));
        if (isset($coin_data[0]->description)) {
            return $coin_data[0]->description;
        } else {
            return false;
        }
    } else {
        CMC_api_data::cmc_select_social_data_api($coin_id);
        $coin_data = $cmcMetaDB->get_coins_desc(array('coin_id' => $coin_id));
        if (isset($coin_data[0]->description)) {
            return $coin_data[0]->description;
        } else {
            return false;
        }
    }
}

/*
|--------------------------------------------------------------------------
| fetching top gainer/ losers
|--------------------------------------------------------------------------
 */
function cmc_get_top_coins($type = "gainers", $show_coins = 10)
{
    $cmcDB = new CMC_Coins;
    if ($type == "gainers") {
        $order_type = 'DESC';
    } else {
        $order_type = 'ASC';
    }
    $coindata = $cmcDB->get_top_changers_coins(array(
        "number" => $show_coins, 'orderby' => 'percent_change_24h',
        'order' => $order_type,
        'volume' => 50000,
    ));
    if (is_array($coindata) && count($coindata) > 0) {
        return $coindata;
    } else {
        return false;
    }
}

function coin_search($old_currency, $single_default_currency,
    $single_page_slug) {
    $html = '';
    $search_links = '';
    $cmc_link = esc_url(home_url($single_page_slug));
    $search = __('search', 'cmc');
    $no_result = __('Unable to find any result', 'cmc');
    $html .= '<div data-slug="' . esc_url(home_url($single_page_slug)) . '/"  data-currency="' . esc_js($old_currency) . '"  data-no-result="' . esc_js($no_result) . '" class="cmc_search" id="custom-templates">
  		<input class="typeahead" type="text" placeholder="' . esc_js($search) . '">
		</div>';
    return $html;
}

/*-----------------------------------------------------------------------|
|             Fetch all coin description created at admin dashboard          |
|                   This function only create a transient.                 |
|------------------------------------------------------------------------|
 */
function get_all_custom_cmc_description()
{

    if (false === ($check = get_transient('cmc-custom-coin-des'))) {
        $custom_description = array(
            'post_type' => 'cmc-description',
            'posts_per_page' => '-1',
        );

        $exists = new WP_Query($custom_description);
        $already_exists = array();
        if ($exists->have_posts()) {
            while ($exists->have_posts()) {
                $exists->the_post();
                // Sanitize the coin ID to prevent potential security issues
                $coin_id = sanitize_text_field(get_post_meta(get_the_ID(), 'cmc_single_settings_des_coin_name', true));
                $already_exists[] = $coin_id;
            }
            wp_reset_postdata();
            set_transient('cmc-custom-coin-des', $already_exists, 24 * HOUR_IN_SECONDS);
            return $already_exists;
        }

    } else {
        return get_transient('cmc-custom-coin-des');
    }

}

/*
|--------------------------------------------------------------------------
| Coin single page main full chart
|--------------------------------------------------------------------------
 */
function cmc_historical_chart_json($coin_id, $day)
{
    $coin_d_arr = array();
    $meta_tbl = new CMC_Coins_historical();
    // $api_obj=new CMC_api_data();
    $historical_all_data = CMC_api_data::cmc_select_historical_data_api($coin_id, $day);

    if (!empty($historical_all_data)) {
        $count = isset($historical_all_data->prices) ? count($historical_all_data->prices) : '';
        for ($i = 0; $i < $count - 1; $i++) {
            $at_time = $historical_all_data->prices[$i][0];
            $coin_price = $historical_all_data->prices[$i][1];
            $coin_vol = $historical_all_data->total_volumes[$i][1];
            $coin_market_cap = $historical_all_data->market_caps[$i][1];
            $coin_d_arr[] = array('date' => $at_time, 'value' => $coin_price, 'volume' => $coin_vol, 'market_cap' => $coin_market_cap);
        }
        if ($day == 2) {
            $meta_tbl->cmc_historical_meta_insert(json_encode(array_slice($coin_d_arr, -24)), $coin_id, $day);

            return array_slice($coin_d_arr, -24);
        } else {
            $meta_tbl->cmc_historical_meta_insert(json_encode($coin_d_arr), $coin_id, $day);
            return $coin_d_arr;
        }

    } else {
        return $meta_tbl->cmc_get_historical_data($coin_id, $day);
    }
}

/*
|--------------------------------------------------------------------
|    This function will update unavailable coins in db
|--------------------------------------------------------------------
|    This must be called for specific post-type only
|--------------------------------------------------------------------
 */
function cmc_update_ua_coins_on_save_post($curr, $show_category)
{
    $cache = get_transient('cmc-category-coins-' . $show_category);

    // Avoid updating database if cache exist or CMC is active
    if (false != $cache) {
        return;
    }

    $available_coins = get_option('ccpwp-available-coins');
    if (!isset($curr) || !is_array($curr) || count($curr) < 0
        || !isset($available_coins) || !is_array($available_coins) || count($available_coins) < 0
    ) {
        return;
    }

    $unavailable_coins = array_diff($curr, $available_coins);

    if (is_array($unavailable_coins) && !empty($unavailable_coins)) {
        //$api_obj=new CCPWP_api_data();
        $api_option = get_option("openexchange-api-settings");
        $api_type = (isset($api_option['select_api'])) ? $api_option['select_api'] : "coingecko";
        $ua_coins_name = ($api_type == "both_coinmarketcap" || $api_type == "coinmarketcap") ? 'ccpwp-unavailable-coins-cmc' : 'ccpwp-unavailable-coins';

        $saved_ua_coins = get_option($ua_coins_name);
        $unavailable_coins = $saved_ua_coins == '' ? $unavailable_coins : array_diff($unavailable_coins, $saved_ua_coins);
        $api_option = get_option("openexchange-api-settings");
        $coingecko_api_cache_time = isset($api_option['select_cache_time']) ? (int) $api_option['select_cache_time'] : 10;
 
        if (is_array($unavailable_coins) && !empty($unavailable_coins)) {
            CMC_api_data::cmc_get_selected_api_ua_data($unavailable_coins, false, true);
            set_transient('cmc-category-coins-' . $show_category, date('H:s:i'), $coingecko_api_cache_time * MINUTE_IN_SECONDS);
        }
    }

}
function cmc_check_api_errors($api_data)
{
    // Get coingecko api end point
    $error_codes = [429, 10006];
    if (isset($api_data->status->error_code) && in_array($api_data->status->error_code, $error_codes)) {
        return true;
    } else {
        return false;
    }

}

function cmc_update_single_coin_data($coin_id)
{
    $cmcDB = new CMC_Coins;
    $coin_data = $cmcDB->get_coins(array('coin_id' => $coin_id));
    $current_datetime = current_time('Y-m-d H:i:s', false);
    $db_timestamp = isset($coin_data[0]->last_updated) ? strtotime($coin_data[0]->last_updated) : 0;
    $current_timestamp = strtotime($current_datetime);
    $time_difference = $current_timestamp - $db_timestamp;
    $minutes = $time_difference / 60;
    $available_coins = get_option('ccpwp-available-coins', []);
    $api_option = get_option("openexchange-api-settings");
    $api_type = (isset($api_option['select_api'])) ? $api_option['select_api'] : "coingecko";
    $ua_coins_name = ($api_type == "both_coinmarketcap" || $api_type == "coinmarketcap") ? 'ccpwp-unavailable-coins-cmc' : 'ccpwp-unavailable-coins';

    $saved_ua_coins = get_option($ua_coins_name, []);
    $coin_tranisent = get_transient('cmc_single_coin' . $coin_id);
    $active_coins = ($saved_ua_coins && $available_coins) ? array_merge($saved_ua_coins, $available_coins) : $available_coins;
    if ($coin_tranisent) {
        return $coin_tranisent;
    }
    if ($minutes > 10 && !in_array($coin_id, $active_coins) && !$coin_tranisent) {

        return CMC_api_data::cmc_get_selected_api_ua_data(array($coin_id), true);
    }
    return false;
}
